<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use think\facade\View;
use think\response\Json;
use app\common\model\Cart as CartModel;

class Cart extends Base
{
    /**
     * get: 购物车列表
     * path: index
     * method: index
     */
    public function index()
    {
        $map = ['uid' => $this->user->id];
        $list = CartModel::getList($map, false, 'update_time', ['product'], 'id,pid,num');
        foreach ($list as $k => $v) {
            $v->title = $v->product->title;
            $v->price = $v->product->price;
            $v->icon = $v->product->icon;
            $v->price = $v->product->price*$v->num;
            unset($v->product);
        }
        return Result::success('获取成功',$list);
    }


    /**
     * post: 加入购物车
     * path: add
     * method: add
     * param: num - {string} 数量
     * param: id - {string} 商品id
     */
    public function add()
    {
        $param = $this->request->post();
        if (!$param['num'] || $param['num'] <= 0) {
            return json(['code' => -1, 'msg' => '数量错误']);
        }
        $add = CartModel::add($this->user, $param['id'], $param['num']);
        if($add['code']>0)
        {
            return Result::success($add['msg']);
        }else{
            return Result::fail($add['msg']);
        }

    }

    /**
     * post: 购物车修改
     * path: edit
     * method: edit
     * param: type - {string} 1增加，2减少，3删除，4清空
     * param: id - {string} 购物车id
     */
    public function edit()
    {
        $param = $this->request->post();
        $edit = CartModel::edit($param['type'], $param['id'], $this->user->id);
        if($edit['code']>0)
        {
            return Result::success($edit['msg']);
        }else{
            return Result::fail($edit['msg']);
        }
    }

    /**
     * post: 提交
     * path: submit
     * method: submit
     * param: cart_id - {string} 购物车id
     */
    public function submit()
    {
        $param = $this->request->post();
        if (!$param['cart_id']) {
            return json(['code' => 1, 'msg' => '请选择要结算的商品']);
        }
        $param['cart_id'] = explode(',', $param['cart_id']);
        $submit = CartModel::submit($param, $this->user);
        if($submit['code']>0)
        {
            return Result::success($submit['msg']);
        }else{
            return Result::fail($submit['msg']);
        }
    }
}


